import { useRef, useEffect, useCallback } from 'react';

export function useResizableDrawer({
  direction,
  drawerKey,
  drawerSize,
  setDrawerSize,
  onClose,
}) {
  const resizeBarRef = useRef(null);

  const onMouseMove = (e) => {
    if (direction === 'left' || direction === 'right') {
      const deltaX = direction === 'left' ? e.clientX - startX : startX - e.clientX;
      setDrawerSize(Math.max(200, initialSize + deltaX));
    } else if (direction === 'bottom' || direction === 'top') {
      const deltaY = direction === 'bottom' ? e.clientY - startY : startY - e.clientY;
      setDrawerSize(Math.max(200, initialSize + deltaY));
    }
  };

  const onMouseUp = () => {
    document.removeEventListener('mousemove', onMouseMove);
    document.removeEventListener('mouseup', onMouseUp);
    if (drawerKey) {
      setDrawerSize((old) => {
        setDrawerSizeToStorage(drawerKey, old);
        return old
      })
    }
  };

  const onMouseDown = (e) => {
    e.preventDefault();
    startX = e.clientX;
    startY = e.clientY;
    console.log(drawerSize)
    initialSize = drawerSize;
    document.addEventListener('mousemove', onMouseMove);
    document.addEventListener('mouseup', onMouseUp);
  }

  const onClosed = useCallback(() => {
    onClose?.();
  }, [onClose]);

  useEffect(() => {
    return () => {
      document.removeEventListener('mousemove', onMouseMove);
      document.removeEventListener('mouseup', onMouseUp);
    };
  }, []);

  const drawerClassName = `resize-drawer-${direction}`;
  const resizeBarClassName = `resize-bar resize-bar-${direction}`;

  return {
    resizeBarRef,
    onMouseDown,
    onClosed,
    drawerClassName,
    resizeBarClassName,
  };
}

export function getDrawerSize(drawerKey, defaultSize) {
  if (!drawerKey) return defaultSize;
  const drawList = JSON.parse(localStorage.getItem('drawList') || '[]');
  const drawer = drawList.find(item => item.key === drawerKey);
  return drawer ? drawer.size : defaultSize;
}

export function setDrawerSize(drawerKey, size) {
  if (!drawerKey) return;
  const drawList = JSON.parse(localStorage.getItem('drawList') || '[]');
  const drawer = drawList.find(item => item.key === drawerKey);
  if (drawer) {
    drawer.size = size;
  } else {
    drawList.push({ key: drawerKey, size });
  }
  localStorage.setItem('drawList', JSON.stringify(drawList));
}

// 用于存储 drawer 尺寸的辅助函数
function setDrawerSizeToStorage(drawerKey, size) {
  setDrawerSize(drawerKey, size);
}

// 用于存储鼠标起始位置的变量
let startX = 0;
let startY = 0;
let initialSize = 0; 